"""
AI Integration Views
AI功能集成API视图
"""
import json
import logging
from datetime import datetime, timedelta
from django.shortcuts import render
from django.utils import timezone
from django.db.models import Count, Avg, Q
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from rest_framework import status, permissions, generics
from rest_framework.decorators import api_view, permission_classes, action
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from .services import (
    question_service, grading_service, analytics_service,
    AIServiceError, AIRateLimitError, AIAPIError
)
from .ai_config import (
    AI_QUESTION_GENERATION_ENABLED, AI_GRADING_ASSISTANT_ENABLED,
    AI_ANALYTICS_ENABLED
)
from .models_clean import (
    AIGeneratedQuestion, AIGradingResult, AIAnalytics,
    AIUsageLog, AIModelMetrics
)

logger = logging.getLogger(__name__)

class BaseAIAPIView(APIView):
    """AI API基类"""
    permission_classes = [permissions.IsAuthenticated]

    def handle_ai_error(self, error, user_id=None):
        """处理AI服务错误"""
        # 记录使用日志
        AIUsageLog.objects.create(
            user_id=user_id,
            service_type=self.get_service_type(),
            request_data={},
            response_data={'error': str(error)},
            response_time=timedelta(seconds=0),
            success=False,
            error_message=str(error)
        )

        if isinstance(error, AIRateLimitError):
            return Response(
                {'error': '请求过于频繁，请稍后再试', 'code': 'RATE_LIMIT'},
                status=status.HTTP_429_TOO_MANY_REQUESTS
            )
        elif isinstance(error, AIAPIError):
            return Response(
                {'error': 'AI服务暂时不可用，请稍后重试', 'code': 'AI_SERVICE_ERROR'},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )
        else:
            return Response(
                {'error': f'服务异常: {str(error)}', 'code': 'INTERNAL_ERROR'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    def get_service_type(self):
        """获取服务类型，子类需要重写"""
        return 'unknown'

    def log_usage(self, user_id, request_data, response_data, response_time, tokens_used=0):
        """记录API使用情况"""
        AIUsageLog.objects.create(
            user_id=user_id,
            service_type=self.get_service_type(),
            request_data=request_data,
            response_data=response_data,
            response_time=response_time,
            tokens_used=tokens_used,
            success=True
        )

class QuestionGenerationView(BaseAIAPIView):
    """智能题目生成API"""

    def get_service_type(self):
        return 'question_generation'

    @csrf_exempt
    def post(self, request):
        """生成题目"""
        if not AI_QUESTION_GENERATION_ENABLED:
            return Response(
                {'error': 'AI题目生成功能已禁用', 'code': 'FEATURE_DISABLED'},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )

        try:
            # 获取请求参数
            subject = request.data.get('subject')
            topic = request.data.get('topic')
            difficulty = request.data.get('difficulty', 'medium')
            question_type = request.data.get('question_type', 'single_choice')
            count = int(request.data.get('count', 1))
            additional_context = request.data.get('additional_context', '')

            # 参数验证
            if not subject or not topic:
                return Response(
                    {'error': '请提供学科和主题', 'code': 'MISSING_PARAMS'},
                    status=status.HTTP_400_BAD_REQUEST
                )

            if count > 10:
                return Response(
                    {'error': '单次最多生成10道题目', 'code': 'TOO_MANY_QUESTIONS'},
                    status=status.HTTP_400_BAD_REQUEST
                )

            # 记录请求开始时间
            start_time = timezone.now()

            # 调用AI服务生成题目
            result = question_service.generate_question(
                subject=subject,
                topic=topic,
                difficulty=difficulty,
                question_type=question_type,
                count=count,
                additional_context=additional_context,
                user_id=str(request.user.id)
            )

            # 计算响应时间
            response_time = timezone.now() - start_time

            if result['success']:
                # 保存生成的题目到数据库
                saved_questions = []
                for question_data in result['questions']:
                    question = AIGeneratedQuestion.objects.create(
                        user=request.user,
                        subject=subject,
                        topic=topic,
                        difficulty=difficulty,
                        question_type=question_type,
                        title=question_data.get('title', ''),
                        content=question_data.get('content', ''),
                        options=question_data.get('options', []),
                        correct_answer=question_data.get('correct_answer', ''),
                        explanation=question_data.get('explanation', ''),
                        estimated_time=question_data.get('estimated_time', 300),
                        score=question_data.get('score', 10),
                        generation_prompt=additional_context,
                        ai_model=result.get('usage', {}).get('model', 'unknown'),
                        generation_tokens=result.get('usage', {}).get('total_tokens', 0)
                    )
                    saved_questions.append({
                        'id': str(question.id),
                        'title': question.title,
                        'content': question.content,
                        'options': question.options,
                        'correct_answer': question.correct_answer,
                        'explanation': question.explanation,
                        'difficulty': question.difficulty,
                        'estimated_time': question.estimated_time,
                        'score': question.score
                    })

                # 记录使用日志
                self.log_usage(
                    user_id=request.user.id,
                    request_data=request.data,
                    response_data={'question_count': len(saved_questions)},
                    response_time=response_time,
                    tokens_used=result.get('usage', {}).get('total_tokens', 0)
                )

                return Response({
                    'success': True,
                    'questions': saved_questions,
                    'total_generated': len(saved_questions),
                    'generation_info': {
                        'subject': subject,
                        'topic': topic,
                        'difficulty': difficulty,
                        'question_type': question_type,
                        'generated_at': result['generated_at']
                    }
                })

            else:
                return Response({
                    'success': False,
                    'error': result.get('error', '生成失败'),
                    'error_code': 'GENERATION_FAILED'
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        except Exception as e:
            logger.error(f"题目生成失败: {str(e)}")
            return self.handle_ai_error(e, request.user.id)

class GradingAssistantView(BaseAIAPIView):
    """AI评分助手API"""

    def get_service_type(self):
        return 'grading_assistant'

    @csrf_exempt
    def post(self, request):
        """AI评分"""
        if not AI_GRADING_ASSISTANT_ENABLED:
            return Response(
                {'error': 'AI评分助手功能已禁用', 'code': 'FEATURE_DISABLED'},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )

        try:
            grading_type = request.data.get('grading_type')

            if grading_type == 'essay':
                return self.grade_essay(request)
            elif grading_type == 'short_answer':
                return self.grade_short_answer(request)
            else:
                return Response(
                    {'error': '不支持的评分类型', 'code': 'INVALID_GRADING_TYPE'},
                    status=status.HTTP_400_BAD_REQUEST
                )

        except Exception as e:
            logger.error(f"AI评分失败: {str(e)}")
            return self.handle_ai_error(e, request.user.id)

    def grade_essay(self, request):
        """作文评分"""
        essay_content = request.data.get('essay_content')
        essay_prompt = request.data.get('essay_prompt', '')
        rubric = request.data.get('rubric', '')
        max_score = float(request.data.get('max_score', 100))

        if not essay_content:
            return Response(
                {'error': '请提供作文内容', 'code': 'MISSING_CONTENT'},
                status=status.HTTP_400_BAD_REQUEST
            )

        start_time = timezone.now()

        result = grading_service.grade_essay(
            essay_content=essay_content,
            essay_prompt=essay_prompt,
            rubric=rubric,
            max_score=max_score,
            user_id=str(request.user.id)
        )

        response_time = timezone.now() - start_time

        if result['success']:
            # 保存评分结果
            grading_result = AIGradingResult.objects.create(
                user=request.user,
                grading_type='essay',
                student_answer=essay_content,
                reference_answer=essay_prompt,
                grading_prompt=rubric,
                ai_score=result['grading']['score'],
                max_score=max_score,
                score_percentage=result['grading']['score_percentage'],
                strengths=result['grading']['strengths'],
                weaknesses=result['grading']['weaknesses'],
                detailed_feedback=result['grading']['detailed_feedback'],
                suggestions=result['grading']['suggestions'],
                ai_model=result.get('usage', {}).get('model', 'unknown'),
                processing_time=response_time,
                tokens_used=result.get('usage', {}).get('total_tokens', 0)
            )

            # 记录使用日志
            self.log_usage(
                user_id=request.user.id,
                request_data=request.data,
                response_data={'score': result['grading']['score']},
                response_time=response_time,
                tokens_used=result.get('usage', {}).get('total_tokens', 0)
            )

            return Response({
                'success': True,
                'grading': result['grading'],
                'grading_id': str(grading_result.id),
                'max_score': max_score
            })

        else:
            return Response({
                'success': False,
                'error': result.get('error', '评分失败')
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def grade_short_answer(self, request):
        """简答题评分"""
        student_answer = request.data.get('student_answer')
        reference_answer = request.data.get('reference_answer', '')
        question = request.data.get('question', '')
        max_score = float(request.data.get('max_score', 10))

        if not student_answer:
            return Response(
                {'error': '请提供学生答案', 'code': 'MISSING_ANSWER'},
                status=status.HTTP_400_BAD_REQUEST
            )

        start_time = timezone.now()

        result = grading_service.grade_short_answer(
            student_answer=student_answer,
            reference_answer=reference_answer,
            question=question,
            max_score=max_score,
            user_id=str(request.user.id)
        )

        response_time = timezone.now() - start_time

        if result['success']:
            # 保存评分结果
            grading_result = AIGradingResult.objects.create(
                user=request.user,
                grading_type='short_answer',
                student_answer=student_answer,
                reference_answer=reference_answer,
                grading_prompt=question,
                ai_score=result['grading']['score'],
                max_score=max_score,
                score_percentage=result['grading']['score_percentage'],
                strengths=result['grading']['strengths'],
                weaknesses=result['grading']['weaknesses'],
                detailed_feedback=result['grading']['detailed_feedback'],
                suggestions=result['grading']['suggestions'],
                ai_model=result.get('usage', {}).get('model', 'unknown'),
                processing_time=response_time,
                tokens_used=result.get('usage', {}).get('total_tokens', 0)
            )

            # 记录使用日志
            self.log_usage(
                user_id=request.user.id,
                request_data=request.data,
                response_data={'score': result['grading']['score']},
                response_time=response_time,
                tokens_used=result.get('usage', {}).get('total_tokens', 0)
            )

            return Response({
                'success': True,
                'grading': result['grading'],
                'grading_id': str(grading_result.id),
                'max_score': max_score
            })

        else:
            return Response({
                'success': False,
                'error': result.get('error', '评分失败')
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class AnalyticsView(BaseAIAPIView):
    """AI分析API"""

    def get_service_type(self):
        return 'analytics'

    @csrf_exempt
    def post(self, request):
        """AI分析"""
        if not AI_ANALYTICS_ENABLED:
            return Response(
                {'error': 'AI分析功能已禁用', 'code': 'FEATURE_DISABLED'},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )

        try:
            analysis_type = request.data.get('analysis_type')

            if analysis_type == 'learning_progress':
                return self.analyze_learning_progress(request)
            elif analysis_type == 'study_recommendations':
                return self.generate_study_recommendations(request)
            else:
                return Response(
                    {'error': '不支持的分析类型', 'code': 'INVALID_ANALYSIS_TYPE'},
                    status=status.HTTP_400_BAD_REQUEST
                )

        except Exception as e:
            logger.error(f"AI分析失败: {str(e)}")
            return self.handle_ai_error(e, request.user.id)

    def analyze_learning_progress(self, request):
        """学习进度分析"""
        performance_data = request.data.get('performance_data', [])

        if not performance_data:
            return Response(
                {'error': '请提供学习数据', 'code': 'MISSING_DATA'},
                status=status.HTTP_400_BAD_REQUEST
            )

        start_time = timezone.now()

        result = analytics_service.analyze_learning_progress(
            user_id=str(request.user.id),
            performance_data=performance_data
        )

        response_time = timezone.now() - start_time

        if result['success']:
            # 保存分析结果
            analytics = AIAnalytics.objects.create(
                user=request.user,
                analysis_type='learning_progress',
                input_data={'performance_data': performance_data},
                analysis_result={'raw_analysis': result['analysis']},
                insights=result['analysis'],
                ai_model=result.get('usage', {}).get('model', 'unknown'),
                processing_time=response_time,
                tokens_used=result.get('usage', {}).get('total_tokens', 0)
            )

            # 记录使用日志
            self.log_usage(
                user_id=request.user.id,
                request_data=request.data,
                response_data={'analysis_length': len(result['analysis'])},
                response_time=response_time,
                tokens_used=result.get('usage', {}).get('total_tokens', 0)
            )

            return Response({
                'success': True,
                'analysis': result['analysis'],
                'analytics_id': str(analytics.id),
                'analyzed_at': result['analyzed_at']
            })

        else:
            return Response({
                'success': False,
                'error': result.get('error', '分析失败')
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def generate_study_recommendations(self, request):
        """生成学习建议"""
        subject = request.data.get('subject', '')
        weak_areas = request.data.get('weak_areas', [])
        performance_data = request.data.get('performance_data', [])

        if not weak_areas and not performance_data:
            return Response(
                {'error': '请提供薄弱知识点或学习数据', 'code': 'MISSING_DATA'},
                status=status.HTTP_400_BAD_REQUEST
            )

        start_time = timezone.now()

        result = analytics_service.generate_study_recommendations(
            user_id=str(request.user.id),
            subject=subject,
            weak_areas=weak_areas,
            performance_data=performance_data
        )

        response_time = timezone.now() - start_time

        if result['success']:
            # 保存建议结果
            analytics = AIAnalytics.objects.create(
                user=request.user,
                analysis_type='study_recommendations',
                input_data={
                    'subject': subject,
                    'weak_areas': weak_areas,
                    'performance_data': performance_data
                },
                analysis_result={'raw_recommendations': result['recommendations']},
                insights='AI生成的学习建议',
                recommendations=result['recommendations'],
                subject=subject,
                ai_model=result.get('usage', {}).get('model', 'unknown'),
                processing_time=response_time,
                tokens_used=result.get('usage', {}).get('total_tokens', 0)
            )

            # 记录使用日志
            self.log_usage(
                user_id=request.user.id,
                request_data=request.data,
                response_data={'recommendations_count': len(result['recommendations'])},
                response_time=response_time,
                tokens_used=result.get('usage', {}).get('total_tokens', 0)
            )

            return Response({
                'success': True,
                'recommendations': result['recommendations'],
                'subject': subject,
                'weak_areas': weak_areas,
                'analytics_id': str(analytics.id),
                'generated_at': result['generated_at']
            })

        else:
            return Response({
                'success': False,
                'error': result.get('error', '建议生成失败')
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class AIUsageStatsView(APIView):
    """AI使用统计API"""
    permission_classes = [permissions.IsAuthenticated]

    def get(self, request):
        """获取用户的AI使用统计"""
        try:
            user_id = request.user.id

            # 基础统计
            total_usage = AIUsageLog.objects.filter(user_id=user_id).count()
            successful_usage = AIUsageLog.objects.filter(
                user_id=user_id, success=True
            ).count()

            success_rate = (successful_usage / total_usage * 100) if total_usage > 0 else 0

            # 按服务类型统计
            service_stats = AIUsageLog.objects.filter(user_id=user_id).values(
                'service_type'
            ).annotate(
                count=Count('id'),
                success_count=Count('id', filter=Q(success=True)),
                avg_tokens=Avg('tokens_used')
            ).order_by('-count')

            # 最近使用记录
            recent_usage = AIUsageLog.objects.filter(
                user_id=user_id
            ).order_by('-created_at')[:10].values(
                'service_type', 'success', 'created_at', 'tokens_used'
            )

            # 本月使用统计
            current_month = timezone.now().replace(day=1)
            monthly_usage = AIUsageLog.objects.filter(
                user_id=user_id,
                created_at__gte=current_month
            ).count()

            return Response({
                'total_usage': total_usage,
                'successful_usage': successful_usage,
                'success_rate': round(success_rate, 2),
                'monthly_usage': monthly_usage,
                'service_breakdown': list(service_stats),
                'recent_usage': list(recent_usage)
            })

        except Exception as e:
            logger.error(f"获取AI使用统计失败: {str(e)}")
            return Response(
                {'error': '获取统计数据失败'},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

class AIGeneratedQuestionsView(generics.ListAPIView):
    """AI生成的题目列表"""
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        queryset = AIGeneratedQuestion.objects.filter(user=self.request.user)

        # 筛选参数
        subject = self.request.query_params.get('subject')
        difficulty = self.request.query_params.get('difficulty')
        question_type = self.request.query_params.get('question_type')
        is_approved = self.request.query_params.get('is_approved')

        if subject:
            queryset = queryset.filter(subject=subject)
        if difficulty:
            queryset = queryset.filter(difficulty=difficulty)
        if question_type:
            queryset = queryset.filter(question_type=question_type)
        if is_approved is not None:
            queryset = queryset.filter(is_approved=is_approved.lower() == 'true')

        return queryset.order_by('-created_at')

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()

        # 手动序列化数据
        questions_data = []
        for question in queryset:
            questions_data.append({
                'id': str(question.id),
                'subject': question.subject,
                'topic': question.topic,
                'difficulty': question.difficulty,
                'question_type': question.question_type,
                'title': question.title,
                'content': question.content,
                'options': question.options,
                'score': question.score,
                'estimated_time': question.estimated_time,
                'is_approved': question.is_approved,
                'usage_count': question.usage_count,
                'created_at': question.created_at.isoformat(),
                'quality_score': float(question.quality_score) if question.quality_score else None
            })

        return Response({
            'count': len(questions_data),
            'results': questions_data
        })

# API端点定义
@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def ai_status(request):
    """AI服务状态检查"""
    return Response({
        'status': 'active',
        'features': {
            'question_generation': AI_QUESTION_GENERATION_ENABLED,
            'grading_assistant': AI_GRADING_ASSISTANT_ENABLED,
            'analytics': AI_ANALYTICS_ENABLED,
        },
        'user_rate_limit': {
            'requests_per_minute': 60,
            'requests_per_hour': 1000,
        }
    })

@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def ai_feedback(request):
    """AI服务反馈"""
    try:
        usage_id = request.data.get('usage_id')
        satisfaction = int(request.data.get('satisfaction', 1))
        feedback_text = request.data.get('feedback', '')

        # 更新使用记录的反馈
        if usage_id:
            usage_log = AIUsageLog.objects.filter(
                id=usage_id, user=request.user
            ).first()
            if usage_log:
                usage_log.user_satisfaction = satisfaction
                usage_log.feedback = feedback_text
                usage_log.save()

        return Response({'success': True})

    except Exception as e:
        logger.error(f"保存AI反馈失败: {str(e)}")
        return Response(
            {'error': '保存反馈失败'},
            status=status.HTTP_500_INTERNAL_SERVER_ERROR
        )